import { BtMessage } from './utils/BtMessage.js'
import { registry } from './api/index.js'


$(document).ready(() => {

    $("#l-btn-captcha").click(function() {
        // 获取验证码
        const btn = $(this)
        btn.attr("disabled", 'true') // 给按钮添加禁止的属性

        let t = 60 // 倒计时60s，并且显示倒计时时间
        btn.text("获取验证码(" + t + ")")
        const handler = setInterval(() => {
            t --
            btn.text("获取验证码(" + t + ")")
            if (!t) {
                clearInterval(handler)
                btn.removeAttr('disabled')
                btn.text("获取验证码")
            }
        }, 1000)
    })

    $("#btn-registry").click(registry_real)
})

const registry_real = () => {

    const btn = $("#btn-registry")
    
    const uname = $("#l-u-uname").val(), pwd = $("#l-u-pwd").val()
    const email = $("#l-e-email").val(), code = $("#l-e-captcha").val()
    if (!uname || !pwd || !email || email.indexOf("@") == -1 || !code) {
        return
    }

    btn.attr("disabled", 'true')
    btn.find(".spinner-border").removeClass("d-none")

    setTimeout(() => {
        registry(uname, pwd, email).then(res => {

            btn.removeAttr("disabled")
            btn.find(".spinner-border").addClass("d-none")
    
            if (res.code != 200) {
                BtMessage({
                    type: 'error',
                    message: res.msg || '注册失败，原因未知!'
                })
                return
            }
    
            // 保存token，跳转回首页
            localStorage.setItem("token", res.data)
            BtMessage({
                type: 'success',
                message: '注册成功!'
            })
            setTimeout(() => {
                window.location.href = "/login.html"
            }, 500)
        })
    }, 500)
    

}